<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/29
 * Time: 15:23
 */

namespace app\api\controller\android\v12;

use app\api\model\OrderModel;
use think\Exception;
use think\Controller;
use think\Request;
use app\api\model\Authority;
use think\Db;

class Artificial extends Controller
{
    protected $us;

    public function _initialize()
    {
        $this->us = Authority::check(1);
    }

    /**
     * 日报参数
     */
    protected function day_param($max = 3)
    {
        $param = Request::instance()->post();
        if (empty($param['start_date'])) {
            r_date(null, 300, "开始时间不能为空");
        }
        if (empty($param['end_date'])) {
            r_date(null, 300, "结束时间不能为空");
        }
        $start = date("Y-m-d", strtotime($param['start_date']));
        $end   = date("Y-m-d", strtotime($param['end_date']));
        //两个时间差的天数
        $day = day_value($start, $end);
        if ($day < 0) {
            r_date(null, 300, "开始时间不能小于结束时间");
        }
        //两个时间差的月数
        $month = month_value($start, $end);
        if ($month > $max) {
            r_date(null, 300, "时间跨度不能超过" . $max . "月");
        }

        return [
            'start_date' => $start,
            'end_date' => $end,
            'start_timestamp' => strtotime($start . ' 00:00:00'),
            'end_timestamp' => strtotime($end . ' 23:59:59'),
            'type' => isset($param['type']) ? $param['type'] : 1,
            'Difference' => isset($param['Difference']) ? $param['Difference'] : 1,
            'day' => $day,
            'month' => $month,
            'user_id' => isset($param['user_id']) ? $param['user_id'] : $this->us['user_id'],
        ];
    }

    public function user_list()
    {
        $cap = db('user')->where('store_id', $this->us['store_id'])->field('reserve,user_id,username')->select();
        r_date($cap, 200);
    }

    /*
     * 材料计算
     */

    public function Cost(OrderModel $orderModel)
    {

        $data     = Authority::param(['order_id', 'type']);
        $order_id = $data['order_id'];
        $de       = db('startup')->where('orders_id', $order_id)->field('sta_time,up_time,con,handover,xiu_id')->find();
        $cap      = $orderModel->ManualSettlement($order_id);

        if(empty($cap['data'])){
            r_date(null, 200);
        }

        $app_user_order_capital_relation = Db::connect(config('database.db2'))->table('app_user_order_capital_relation')->whereIn('user_id', $de['xiu_id'])->join('app_user', 'app_user.id=app_user_order_capital_relation.user_id', 'left')->field('app_user.username,app_user.id,app_user_order_capital_relation.capital_id')->where('order_id', $order_id)->select();
        $app_user1                       = Db::connect(config('database.db2'))->table('app_user_order')->whereIn('user_id', $de['xiu_id'])->join('app_user', 'app_user.id=app_user_order.user_id', 'left')->field('app_user.username,app_user.id')->where('order_id', $order_id)->select();
        //本店铺所有的师傅
        $appUser     = Db::connect(config('database.db2'))->table('app_user')->where('store_id', $this->us['store_id'])->where('status', 1)->group('work_type_id')->field('id,username,work_type_id')->select();
        $almighty    = [];
        $carpentry   = [];
        $painter     = [];
        $Bricklayer  = [];
        $electrician = [];
        $KnockDown   = [];
        foreach ($appUser as $k => $v) {
            switch ($v['work_type_id']) {
                //全能工
                case 1:
                    $almighty[] = $v;
                    break;
                //木工
                case 2:
                    $carpentry[] = $v;
                    break;
                //漆工
                case 3:
                    $painter[] = $v;
                    break;
                //砖工
                case 4:
                    $Bricklayer[] = $v;
                    break;
                //电工
                case 5:
                    $electrician[] = $v;
                    break;
                //打拆协作
                case 8:
                    $KnockDown[] = $v;
                    break;

            }
        }

        $result   = array();
        $tageList = [];

        if ($data['type'] == 1) {
            foreach ($cap['data'] as $k => $v) {
                switch ($v['id']) {
                    //拆除类
                    case 1:
                        $cap['data'][$k]['mastUsername'] = empty($KnockDown) ? $almighty : $KnockDown;
                        break;
                    //油漆工类 防水类
                    case 2:
                    case 6:
                        $cap['data'][$k]['mastUsername'] = empty($painter) ? $almighty : $painter;
                        break;
                    //泥瓦工类
                    case 3:
                        $cap['data'][$k]['mastUsername'] = empty($Bricklayer) ? $almighty : $Bricklayer;
                        break;
                    //木工类
                    case 4:
                        $cap['data'][$k]['mastUsername'] = empty($carpentry) ? $almighty : $carpentry;
                        break;
                    //水电工类
                    case 5:
                        $cap['data'][$k]['mastUsername'] = empty($electrician) ? $almighty : $electrician;
                        break;
                    //其他
                    default :
                        $cap['data'][$k]['mastUsername'] = [];
                        break;

                }

            }
            if (!empty($app_user_order_capital_relation)) {
                foreach ($cap['data'] as $k => $v) {
                    $users = [];
                    foreach ($app_user_order_capital_relation as $value) {
                        if (!empty($value['capital_id']) && $value['capital_id'] == $v['projectId']) {
                            $users[] = $value;
                        }

                    }

                    $cap['data'][$k]['mastUsername'] = array_merge($users, $v['mastUsername']);
                }
            }

        } else {
            if (!empty($app_user_order_capital_relation)) {
                foreach ($cap['data'] as $k => $v) {
                    $users = [];
                    foreach ($app_user_order_capital_relation as $value) {
                        if (!empty($value['capital_id']) && $value['capital_id'] == $v['projectId']) {
                            $users[] = $value;
                        }

                    }
                    $cap['data'][$k]['mastUsername'] = $users;
                }
            } else {
                foreach ($cap['data'] as $k => $v) {
                    $cap['data'][$k]['mastUsername'] = $app_user1;
                }

            }

        }
        $type = 0;
        if (!empty($app_user1)) {
            $type = 1;
        }

        foreach ($cap['data'] as $k => $v) {
            $result[$v['titles']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['titles'] = $k;
            $schemeTag['data']  = $result[$k];
            $tageList[]         = $schemeTag;
        }
        $cap['sta_time'] = !empty($de['sta_time']) ? date('Y-m-d', $de['sta_time']) : '';
        $cap['up_time']  = !empty($de['up_time']) ? date('Y-m-d', $de['up_time']) : '';
        $cap['handover'] = !empty($de['handover']) ? unserialize($de['handover']) : null;
        $cap['con']      = $de['con'];
        $cap['data']     = $tageList;
        $cap['type']     = $type;
        r_date($cap, 200);
    }

    /*
     * 提交人工报价
     */
    public function category()
    {
        $data = Request::instance()->post();
        $op   = json_decode($data['company'], true);
        db()->startTrans();
        try {

                foreach ($op as $item) {
                    db('capital')->where(['capital_id' => $item['projectId']])->update(['labor_cost' => $item['pri'], 'material' => $item['material'], 'revised' => 1]);
                    $app_user_order_capital = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id', $item['projectId'])->whereNull('deleted_at')->select();
                    $work_time              = array_sum(array_column($app_user_order_capital, 'work_time'));
                    if ($work_time == 0) {
                        if ($app_user_order_capital) {
                            Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id', $item['projectId'])->update(['personal_price' => 0, 'total_price' => $item['pri']]);
                        }
                    } else {
                        foreach ($app_user_order_capital as $value) {
                            $orderCapital      = db('large_reimbursement', config('database.zong'))->where('order_id', $value['order_id'])->where('user_id', $value['user_id'])->where('status', 1)->sum('money');
                            $orderCapitalMoney = db('app_user_order_capital', config('database.db2'))->where('order_id', $value['order_id'])->where('id', '<>', $value['id'])->where('user_id', $value['user_id'])->whereNull('deleted_at')->sum('personal_price');
                            if ($orderCapital > $orderCapitalMoney + sprintf('%.2f', $item['pri'] * $value['work_time'] / $work_time)) {
                                throw new Exception('过审大工地结算金额超过清单工资');
                            }

                        }

                        foreach ($app_user_order_capital as $value) {
                            if ($value['work_time'] == 0) {
                                Db::connect(config('database.db2'))->table('app_user_order_capital')->where('id', $value['id'])->update(['personal_price' => 0, 'total_price' => $item['pri']]);
                            } else {
                                Db::connect(config('database.db2'))->table('app_user_order_capital')->where('id', $value['id'])->update(['personal_price' => sprintf('%.2f', $item['pri'] * $value['work_time'] / $work_time), 'total_price' => $item['pri']]);

                            }

                        }
                    }
                }


            $data['shi_id'] = empty(json_decode($data['leader'], true)) ? '' : implode(array_unique(array_column(json_decode($data['leader'], true), 'masterId')), ',');
            $leader         = empty(json_decode($data['leader'], true)) ? null : array_unique(array_column(json_decode($data['leader'], true), 'masterId'));
            $leaders        = json_decode($data['leader'], true);
            $leaderList     = [];
            if (!empty($leader)) {
                foreach ($leader as $k => $item) {
                    foreach ($leaders as $datum) {
                        if ($item == $datum['masterId']) {
                            $leaderList[$k]['user_id'] = $item;
                            $leaderList[$k]['leader']  = 0;
                        }
                    }
                }
            }

            $res = db('startup')->where(['orders_id' => $data['order_id']])->find();
            if (!isset($data['type'])) {
                if (empty($data['shi_id']) && !empty($data['shi_id'])) {
                    throw new Exception('请至少选择一个师傅');
                }
                $o = ['con' => $data['con'],//备注
                    'sta_time' => empty($data['sta_time']) ? '' : strtotime($data['sta_time']),
                    'up_time' => empty($data['up_time']) ? '' : strtotime($data['up_time']),
                    'xiu_id' => $data['shi_id'],
                    'handover' => !empty($data['handover']) ? serialize(json_decode($data['handover'], true)) : '',
                ];
                if ($res) {
                    db('startup')->where('orders_id', $data['order_id'])->update($o);
                } else {
                    $o['orders_id'] = $data['order_id'];
                    $res            = db('startup')->insertGetId($o);

                    db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['startup_id' => $res]);
                }

                $us = db('order')->field('order.ification,order.telephone,co.con_time,co.contracType,order.pro_id2,order.tui_jian,order.tui_role,order.pro_id')->join('contract co', 'order.order_id=co.orders_id', 'left')->where('order_id', $data['order_id'])->find();

                $ca                    = db('envelopes')->where(['ordesr_id' => $data['order_id'], 'type' => 1])->field('give_money,gong')->find();
                if(!empty($data['shi_id'])){
                    $uss['order_id']       = $data['order_id'];
                    $uss['remark']         = $data['con'];
                    $uss['user_ids']       = $data['shi_id'];
                    $uss['plan_start_at']  = strtotime($data['sta_time']);
                    $uss['plan_end_at']    = strtotime($data['up_time']);
                    $uss['plan_work_time'] = $ca['gong']; //师傅ID
                    $uss['leaders']    = $data['leader']; //师傅ID
                    $uss['leader']     = json_encode($leaderList); //师傅ID
                    $uss['ascription'] = $this->us['store_id']; //师傅ID
                    $uss['con_time']   = $us['con_time']; //师傅ID
                    $uss['store_id']   = $this->us['store_id']; //师傅ID

                    $result  = send_post(UIP_SRC . "/support-v1/order/add", $uss);
                    $results = json_decode($result, true);

                    if ($results['code'] != 200) {
                        throw new Exception($results['msg']);

                    }
                }

            }
            db()->commit();
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /*
     * 店铺成交量
     */
    public function turnover_day(OrderModel $orderModel)
    {
        $timedata = $this->day_param(3);

        $start_timestamp = $timedata['start_timestamp'];
        // $end_timestamp = $timedata['end_timestamp'];
        $day              = $timedata['day'];
        $order_num        = [];
        $order_turnover   = [];
        $order_cost       = [];
        $material_usage   = [];
        $reimbursement    = [];
        $profit           = [];
        $order_unit_price = [];
        for ($i = $day; $i > -1; $i--) {
            $_begin = $start_timestamp + $i * 86400;
            $_end   = $start_timestamp + 86399 + $i * 86400;
            $order  = $orderModel->order_list($timedata['type'], $_begin, $_end, empty($timedata['user_id']) ? $this->us['user_id'] : $timedata['user_id'], $this->us['store_id']);

            //成交额
            $turnover         = order_for_turnover($order);
            $order_num[]      = [
                'time' => date('Y/m/d', $_begin),
                'data' => count($order),
            ];
            $order_turnover[] = [
                'time' => date('Y/m/d', $_begin),
                'data' => $turnover,
            ];

            if ($timedata['Difference'] == 4) {
                if ($turnover > 0) {
                    $unit_price = sprintf("%.2f", ($turnover / count($order)));
                } else {
                    $unit_price = 0;
                }
                $order_unit_price[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => $unit_price,
                ];
            } elseif ($timedata['Difference'] == 5) {

                //预计人工费
                $order_cost[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_artificial($order),
                ];
                //预计材料费
                $material_usage[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_Finance($order),
                ];
                //报销费(只要实际报销)
                $reimbursement[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_outlay($order),
                ];
                $profit[]        = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => sprintf("%.2f", ($turnover - order_for_artificial($order) - order_for_Finance($order) - order_for_outlay($order))),
                ];

            } else if ($timedata['Difference'] == 6) {

                //实际人工费
                $order_cost[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_reality_artificial($order),
                ];
                //实际材料费
                $material_usage[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_reality_material($order),
                ];
                //报销费(只要实际报销)
                $reimbursement[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_outlay($order),
                ];
                $profit[]        = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => sprintf("%.2f", ($turnover - order_for_reality_artificial($order) - order_for_reality_material($order) - order_for_outlay($order))),
                ];
            }


        }
        r_date(['order_num' => $order_num, 'order_turnover' => $order_turnover, 'order_unit_price' => $order_unit_price, 'order_cost' => $order_cost, 'material_usage' => $material_usage, 'reimbursement' => $reimbursement, 'profit' => $profit], 200, '操作成功');

    }

    /*
     * 客户惊喜服务添加
     */
    public function customerSurpriseService()
    {
        $data  = Authority::param(['order_id', 'content', 'images', 'video']);
        $state = \db('order')->where('order_id', $data['order_id'])->value('state');
        \db('surprise_service_record', config('database.zong'))->insert([
            'order_id' => $data['order_id'],
            'source_type' => 1,
            'source_user' => $this->us['user_id'],
            'order_state' => $state,
            'content_text' => $data['content'],
            'file_images' => $data['images'],
            'file_video' => empty($data['video']) ? '' : $data['video'],
            'add_time' => time(),
        ]);
        r_date(null, 200);
    }

    /*
        * 客户惊喜服务列表
        */
    public function customerSurpriseServiceList()
    {
        $data                    = Authority::param(['orderId']);
        $surprise_service_record = \db('surprise_service_record', config('database.zong'))->where('order_id', $data['orderId'])->select();
        foreach ($surprise_service_record as $k => $list) {
            if ($list['source_type'] == 2) {
                $surprise_service_record[$k]['username'] = '师傅' . Db::connect(config('database.db2'))->table('app_user')->where('id', $list['source_user'])->value('username');
            } else {
                $surprise_service_record[$k]['username'] = '店长' . \db('user')->where('user_id', $list['source_user'])->value('username');
            }
            $surprise_service_record[$k]['file_images'] = json_decode($list['file_images'], true);
            $surprise_service_record[$k]['file_video']  = json_decode($list['file_video'], true);
            $surprise_service_record[$k]['add_time']    = date('Y-m-d H:i:s', $list['add_time']);
        }

        r_date($surprise_service_record, 200);
    }


}